//
//  RelationshipVC.swift
//  HLCalc
//
//  Created by 黄龙 on 2023/10/7.
//

import UIKit
import JavaScriptCore

class RelationshipVC: UIViewController {
    var fatherBtn: CalcButton?
    var motherBtn: CalcButton?
    var husbandBtn: CalcButton?
    var wifeBtn: CalcButton?
    var sonBtn: CalcButton?
    var daughterBtn: CalcButton?
    var brotherBtn: CalcButton?
    var youngerBrotherBtn: CalcButton?
    var sisterBtn: CalcButton?
    var youngerSisterBtn: CalcButton?
    var clearEntryBtn: CalcButton?
    var allClearBtn: CalcButton?
    var convertBtn: CalcButton?
    var equalBtn: CalcButton?

    var leftTopBtn:UIButton?
    
    let resultLabel: UILabel = {
        let tmpLabel = UILabel()
        tmpLabel.textColor = .orange
        tmpLabel.font = .systemFont(ofSize: 36)
        tmpLabel.textAlignment = .right
        tmpLabel.adjustsFontSizeToFitWidth = true
        tmpLabel.numberOfLines = 1
        tmpLabel.text = "自已"
        return tmpLabel
    }()
    
    let enterLabel: VerticalLabel = {
        let tmpLabel = VerticalLabel()
        tmpLabel.textColor = .label
        tmpLabel.font = .systemFont(ofSize: 28)
        tmpLabel.textAlignment = .right
        tmpLabel.adjustsFontSizeToFitWidth = true
        tmpLabel.numberOfLines = 0
        return tmpLabel
    }()
    
    private var jsContext: JSContext? { //import JavaScriptCore
        guard let jsContext = JSContext(),
            let hgPath = Bundle.main.path(forResource: "relationship.min", ofType: "js"),
            let js = try? String(contentsOfFile: hgPath)
            else { return nil }
        
        let _ = jsContext.evaluateScript(js)
        return jsContext
    }
    
    private func refreshRelative() {
        let res = relatives
        relatives = res
    }
    
    private var relatives: [String] = [] {
        didSet {
            let text = relatives.joined(separator: "的")
            if text.isEmpty {
                enterLabel.text = ""
                resultLabel.text = "自已"
                return
            }
            
            enterLabel.text = text
            
//女性则wife为false，hasband为true
            if ["妈妈", "老婆", "女儿", "姐姐", "妹妹"].contains(relatives.last ?? "")  {
                wifeBtn?.isEnabled = false
                husbandBtn?.isEnabled = true
            } else {
                wifeBtn?.isEnabled = true
                husbandBtn?.isEnabled = false
            }

            if relatives.count > 15 {
                Vibrations.warning.vibrate()
                resultLabel.text = "关系有点远，年长就叫老祖宗吧~"
                return
            }
            
            relationship(text: text)
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .systemBackground
        
        initUI()
    }
    
    override func viewDidAppear(_ animated:Bool){
        super.viewDidAppear(animated)
        self.setNeedsStatusBarAppearanceUpdate() //使prefersStatusBarHidden生效
        if leftTopBtn != nil{
            UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {
                let translate = CGAffineTransformMakeTranslation(0, 0)
                let rotate = CGAffineTransformMakeRotation(90 * CGFloat(Double.pi / 180))
                self.leftTopBtn!.transform = CGAffineTransformConcat(translate, rotate)
            }
        }
    }
    
//控制顶部时间栏的显示与否
    override var prefersStatusBarHidden: Bool {
//prefersStatusBarHidden在viewDidLoad之后，viewDidAppear之前触发(此时不会生效)
//要使VC打开即生效，需在viewDidAppear里调用setNeedsStatusBarAppearanceUpdate刷新生效
        return true  //设置屏幕是否全屏，true=全屏 ,ViewLoad后会触发此，但首次启动后并不会生效
    }
    

    func initUI(){
        var topbarHeight = 24.0
        if let topbar = UserDefaults.standard.value(forKey: "topbar.height.in.fullstate") as? CGFloat {
            //UIDevice.ui_statusBarHeight()+24 //因为mainVC设置了全屏，会导致present弹出VC时UIDevice.ui_statusBarHeight=0
            let listBtn = UIButton(frame: CGRect(x: 15, y: topbar-40, width: 40, height: 40))
            view.addSubview(listBtn)
            listBtn.setImage(UIImage(named: "menu_exchange"), for: .normal)
            listBtn.addActionWithBlock { sender in
                Vibrations.success.vibrate()
                self.dismiss(animated: false)
            }
            leftTopBtn = listBtn
            
            let titleLabel = UILabel(frame: CGRect(x: 15+40, y: topbar-40, width: screen_W-2*55, height: 40))
            view.addSubview(titleLabel)
            titleLabel.text = "亲戚称谓计算"
            titleLabel.textColor = UIColor("ea7b39")
            titleLabel.font = .boldSystemFont(ofSize: 16)
            titleLabel.textAlignment = .center
            
            topbarHeight = topbar
        }

        //3行4列
        let perWidth = screen_W/4
        let perHeight = perWidth
        let bottomJG = UIDevice.ui_safeDistanceBottom()
        let bottomHeight = perHeight*4+bottomJG
        let bottomView = UIView(frame: CGRect(x: 0, y: screen_H-bottomHeight, width: screen_W, height: bottomHeight))
        view.addSubview(bottomView)
        bottomView.backgroundColor = .secondarySystemBackground
        bottomView.layer.cornerRadius = 5
        
        view.addSubview(resultLabel)
        resultLabel.frame = CGRect(x: 10, y: bottomView.frame.minY - perHeight, width: screen_W-20, height: perHeight)
        view.addSubview(enterLabel)
        enterLabel.frame = CGRect(x: 10, y: topbarHeight + 5, width: screen_W-20, height: resultLabel.frame.minY - 5.0 - topbarHeight - 5.0)
        enterLabel.text = ""
        enterLabel.setVerticalAlignment(.VerticalAlignmentBottom)
        
        let btnTitles = ["父","母","CE","AC","夫","妻","子","女","兄","弟","姐","妹"]
        var iLeft = 0.0
        var iTop = 0.0
        
        for i in 0 ..< 3{
            for j in 0 ..< 4{
                let tmpView = UIView(frame: CGRect(x: iLeft, y: iTop, width: perWidth, height: perWidth))
                bottomView.addSubview(tmpView)
                iLeft += perWidth
                let button = CalcButton(frame: CGRect(x: 5, y: 5, width: perWidth-10, height: perHeight-10))
                tmpView.addSubview(button)
                let iTag = i*4+j
                button.setTitle(btnTitles[iTag], for: .normal)
                button.tag = iTag+100
                button.addActionWithBlock { sender in
                    if 2 == sender.tag-100{
                        self.pressRebackButton()
                    }else if 3 == sender.tag-100{
                        self.pressClearButton()
                    }else{
                        self.pressCallButton(sender as! CalcButton)
                    }
                }
                switch iTag {
                case 0:
                    fatherBtn = button
                case 1:
                    motherBtn = button
                case 2:
                    clearEntryBtn = button
                case 3:
                    allClearBtn = button
                case 4:
                    husbandBtn = button
                case 5:
                    wifeBtn = button
                case 6:
                    sonBtn = button
                case 7:
                    daughterBtn = button
                case 8:
                    brotherBtn = button
                case 9:
                    youngerBrotherBtn = button
                case 10:
                    sisterBtn = button
                case 11:
                    youngerSisterBtn = button
                default:
                    fatherBtn = button
                }
            }
            iTop += perHeight
            iLeft = 0
        }
        //最后一行,互查+=
        let changeBgView = UIView(frame: CGRect(x: 0, y: iTop, width: 2*perWidth, height: perHeight))
        bottomView.addSubview(changeBgView)
        let changeButton = CalcButton(frame: CGRect(x: 5, y: 5, width: 2*perWidth-10, height: perHeight-10))
        changeBgView.addSubview(changeButton)
        changeButton.setTitle("⇋", for: .normal)
        changeButton.addActionWithBlock { sender in
            Vibrations.medium.vibrate()
            sender.isSelected.toggle()
            self.pressConvertButton()
        }
        convertBtn = changeButton

        let dengBgView = UIView(frame: CGRect(x: 2*perWidth, y: iTop, width: 2*perWidth, height: perHeight))
        bottomView.addSubview(dengBgView)
        let dengButton = CalcButton(frame: CGRect(x: 5, y: 5, width: 2*perWidth-10, height: perHeight-10))
        dengBgView.addSubview(dengButton)
        dengButton.setTitle("＝", for: .normal)
        dengButton.addActionWithBlock { sender in
            self.pressEqualButton()
        }
        equalBtn = dengButton
        
        updateTheme()
    }
    
    private func updateTheme() {
        let isDarkSence = self.isDarkMode()
        self.setDarkMode(isDarkSence)
        
        UIView.animate(withDuration: 0.25) {
            [self.fatherBtn, self.motherBtn, self.husbandBtn, self.wifeBtn, self.sonBtn, self.daughterBtn,
             self.brotherBtn, self.youngerBrotherBtn, self.sisterBtn, self.youngerSisterBtn,
             self.clearEntryBtn, self.allClearBtn, self.convertBtn, self.equalBtn
                ].forEach { $0?.colorTheme = isDarkSence ? .dark : .light }
        }
        setNeedsStatusBarAppearanceUpdate()
    }
    
}

extension RelationshipVC{
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
//前后台切换时更新显示
        if #available(iOS 13.0, *) {
            updateTheme()
        }
    }
}

//MARK: - 计算关系
extension RelationshipVC{
    /// text: 输入的文本
    /// sex: 自己的性别：0女性,1男性
    /// reverse: 称呼方式：true对方称呼我,false我称呼对方
    private func relationship(text: String) {
        let reverse = convertBtn?.isSelected
        let script = "relationship({text: '\(text)', sex: \(-1), type: 'default', reverse: \(reverse! ? "true" : "false")})"
        let res = jsContext?.evaluateScript(script).toString()
        resultLabel.text = res

        if res?.isEmpty == true {
            Vibrations.error.vibrate()
            resultLabel.text = "貌似他/她跟你不是很熟哦!"
        }
    }
}

//MARK: - 按钮事件
extension RelationshipVC{
    private func convertToRelation(text: String) -> String? {
        switch text {
        case "父":
            return "爸爸"
        case "母":
            return "妈妈"
        case "夫":
            return "老公"
        case "妻":
            return "老婆"
        case "子":
            return "儿子"
        case "女":
            return "女儿"
        case "兄":
            return "哥哥"
        case "弟":
            return "弟弟"
        case "姐":
            return "姐姐"
        case "妹":
            return "妹妹"
        default:
            return nil
        }
    }
    
    func pressCallButton(_ sender: CalcButton) {
        Vibrations.selection.vibrate()
        guard let text = sender.currentTitle, text.count > 0,
        let relation = convertToRelation(text: text) else { return }
        relatives.append(relation)
    }
    
    private func renewBtnState() {
        wifeBtn?.isEnabled = true
        husbandBtn?.isEnabled = true
    }
    
    func pressRebackButton(){
        Vibrations.light.vibrate()
        if relatives.count > 0 {
            renewBtnState()
            relatives.removeLast()
        }
    }
    
    func pressClearButton(){
        Vibrations.light.vibrate()
        renewBtnState()
        relatives.removeAll()
    }
    
    func pressConvertButton(){
        Vibrations.light.vibrate()
        refreshRelative()
    }
    
    func pressEqualButton(){
        Vibrations.light.vibrate()
        refreshRelative()
    }
    
}
